package com.gemantic.user.controller;

import java.util.Map;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.gemantic.result.PageResponse;
import com.gemantic.result.Response;
import com.gemantic.result.Responses;
import com.gemantic.user.model.User;
import com.gemantic.user.service.UserService;

/**
 *
 *@author wangsf
 *@date 2017年7月8日 下午10:18:44
 *
 */
@Api(value = "UserController", description = "客户信息管理")
@Controller
public class UserController {
	
	private final static Logger log = LoggerFactory.getLogger(UserController.class);
	
	@Value("${localServerLoginUrl}")
	String localServerLoginUrl;
	
	@Value("${casServerLogoutUrl}")
	String casServerLogoutUrl;

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String loginForm(Model model){
		model.addAttribute("user", new User());
		log.info("=====login=======");
		return "redirect:" + localServerLoginUrl;
	}
	
	@ApiOperation(value="用户登录")
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(@Valid User user, BindingResult result, RedirectAttributes attributes){
		if (result.hasErrors()){
			return "login";
		}

		String username = user.getUsername();
		UsernamePasswordToken token = new UsernamePasswordToken(username, user.getPassword());
		Subject currentUser = SecurityUtils.getSubject();
		try {
			// 将调用MyShiroRealm.doGetAuthenticationInfo()方法
			currentUser.login(token);
		} catch (AuthenticationException e){
			if (e instanceof UnknownAccountException){
				attributes.addFlashAttribute("message", "未知账户");
			} else if (e instanceof IncorrectCredentialsException){
				attributes.addFlashAttribute("message", "密码不正确");
			} else if (e instanceof LockedAccountException){
				attributes.addFlashAttribute("message", "账户已锁定");
			} else if (e instanceof ExcessiveAttemptsException){
				attributes.addFlashAttribute("message", "用户名或密码错误次数超限");
			} else {
				e.printStackTrace();
				attributes.addFlashAttribute("message", "用户名或密码不正确");
			}
		}
		if (currentUser.isAuthenticated()){
			return "redirect:/user";
		} else {
			token.clear();
			return "redirect:" + localServerLoginUrl;
		}
	}
	@ApiOperation(value="用户退出")
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(RedirectAttributes attributes){
		SecurityUtils.getSubject().logout();
		attributes.addFlashAttribute("message", "您已安全退出");
//		return "redirect:/login";
		return "redirect:" + casServerLogoutUrl;
	}

	@RequestMapping("/403")
	public String unauthorizedRole(){
		return "403";
	}
	
	@ApiOperation(value="查询用户信息")
	@RequestMapping("/user")
	public String getUserList(Map<String, Object> model){
		return "user";
	}
	
	/*@ApiOperation(value="查询用户信息")
	@RequestMapping("/user")
	public ResponseEntity<Response<PageResponse<User>>> getUserList(@RequestParam(value = "cp", defaultValue = "1") Integer cp,
			@RequestParam(value = "ps", defaultValue = "2") Integer ps) {
		Sort sort = new Sort(Sort.Direction.DESC, "id");
		PageResponse<User> pageResponse = new PageResponse<User>();
		Pageable pageable = new PageRequest(cp - 1, ps, sort);
		Page<User> psc = userService.findAll(pageable);
		pageResponse.setList(psc.getContent());
		pageResponse.setCurrentPage(psc.getNumber());
		pageResponse.setPageSize(psc.getSize());
		pageResponse.setTotalPage(psc.getTotalPages());
		pageResponse.setTotalCountInt((int) psc.getTotalElements());

		log.info("结果：" + pageResponse.toString());
		return Responses.ok(pageResponse);
	}

	@RequestMapping("/user/edit/{id}")
	public String toUserEditPage(@PathVariable int id){
		return "user_edit";
	}*/
}
